import { fileURLToPath, URL } from 'node:url'

import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import svgLoader from 'vite-svg-loader'

import { viteBuildInfo } from "./build/info";

// https://vitejs.dev/config/
/* export default defineConfig({
  plugins: [
    vue(),
  ],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  }
}) */

const warpperEnv = (envConf: any) => {
  /** 此处为默认值 */
  const ret: any = {};
  for (const envName of Object.keys(envConf)) {
    let realName = envConf[envName].replace(/\\n/g, "\n");
    realName =
      realName === "true" ? true : realName === "false" ? false : realName;
    if (envName === "VITE_PORT") {
      realName = Number(realName);
    }
    ret[envName] = realName;
    if (typeof realName === "string") {
      process.env[envName] = realName;
    } else if (typeof realName === "object") {
      process.env[envName] = JSON.stringify(realName);
    }
  }
  return ret;
};

// Vite 默认是不加载 .env 文件的,使用loadEnv 函数来加载指定的 .env 文件
export default defineConfig(({ command, mode }) => {
  console.log('---command:', command, '----mode:', mode)
  const root = process.cwd()
  console.log('root:', root)
  // const env = warpperEnv(loadEnv(mode, root))
  const env = loadEnv(mode, root)
  // 如果参数显示波浪线 - port数据类型不对导致的
  const { VITE_PORT } = env
  console.log(VITE_PORT)
  return {
    // vite 配置
    plugins: [
      vue(),
      svgLoader(),
      viteBuildInfo()
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
        replacement: 'vue-i18n/dist/vue-i18n.cjs.js', //解决i8n警告
      }
    },
    server: {
      port: Number(VITE_PORT),
      host: "0.0.0.0",
      // open: true
    }
  }
})